package cn.gok.controller;

import cn.gok.dao.SqlDao;
import cn.gok.service.SqlService;
import cn.gok.tool.Compare;
import cn.gok.tool.Jdbc;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/")
public class SqlController {

    @PostMapping(value = "/bind")
    @ResponseBody
    public JSONObject bind(@RequestBody JSONObject json){
//        System.out.println("第一次测试，编程开始啦！");
        JSONObject res=new JSONObject();
        String port=json.getString("port");
        String database=json.getString("database");
        String username=json.getString("username");
        String password=json.getString("password");
        String url=json.getString("url");
//        List sql=(ArrayList)json.get("sql");
//        System.out.println(driver);
//        System.out.println(username);
//        System.out.println(url);
//        System.out.println(password);
        //可以正常获取sql语句
//        System.out.println(sql.get(1));
//        建立链接
        Compare compare=new Compare();
        Jdbc jdbc=new Jdbc();
        url=compare.tourl(url,port,database);
        jdbc.setURL(url);
        jdbc.setUser_Name(username);
        jdbc.setUser_PSW(password);
        SqlDao dao=new SqlDao();
        List linkres=dao.link(jdbc);
//        建立数据库链接
        if (linkres!=null){
            res.put("code",1);
            res.put("msg","获取链接成功。。。");
            res.put("data",linkres);
        }else{
            res.put("code",0);
            res.put("msg","获取链接失败。。。");
        }
        return res;
    }
//    根据发来的sql语句，进行验证
    @PostMapping(value = "/validation")
    @ResponseBody
    public JSONObject validation(@RequestBody JSONObject json){
        SqlService sqlService=new SqlService();
        return sqlService.selvalidation(json);
    }

//    @PostMapping(value = "/test")
//    @ResponseBody
//    public  void test(@RequestBody JSONObject json){
//        String sql=json.getString("sql");
//        System.out.println(sql);
//        String[] sqls=sql.split(";");
//        for (int i = 0; i <sqls.length ; i++) {
//            System.out.println("第"+i+"句sql:"+sqls[i]);
//        }
//    }
}
